<?php
session_start();

/**
 * Script used to store a new element in the databse
 */

// Return json encoded data
header ('Content-type: application/json');

require_once '../core/db.php';

// Check if user owns this page:
$sql = 'SELECT userId from sitePages WHERE pageId = ?';
$sth = $db->prepare ($sql);
$sth->execute (array ($_POST['pageId']));
$res= $sth->fetch (PDO::FETCH_ASSOC);
$ok = ($res['userId']==$_SESSION['user']) ? 1:0;

// If user is logged in and own the page, insert new element:
if(isset($_SESSION['user']) && $ok==1) {
    if(isset($_POST['carousel'])) {
       $sql = 'INSERT INTO siteElement (pageId, siteUserID, elementText, elementIndex, showDate, isCarousel) VALUES (?, ?, ?, ?, ?, ?)';
    }
    else {
       $sql = 'INSERT INTO siteElement (pageId, siteUserID, elementTitle, elementText, elementIndex, showDate) VALUES (?, ?, ?, ?, ?, ?)';
    }
    $sth = $db->prepare ($sql);
    if(isset($_POST['carousel'])) {
       $res = $sth->execute (array ($_POST['pageId'], $_SESSION['user'], $_POST['content'], $_POST['index'], 0, 1));
    }
    else {
       $res = $sth->execute (array ($_POST['pageId'], $_SESSION['user'], $_POST['title'], $_POST['content'], $_POST['index'], $_POST['showDate']));
    }
    
    
    if ($res==1)
    	echo json_encode (array ('ok'=>'OK', 'message' => 'Nytt element ble opprettet.'));
    else
    	echo json_encode (array ('message'=>'Kunne ikke lagre element i databasen.'));
} 
else {
    echo json_encode (array ('message'=>'Du kan ikke opprette et element uten å være logget inn og/eller eie denne siden.'));
}
?>